package com.sykj.util;

import java.util.concurrent.TimeUnit;

import org.springframework.cache.Cache;
import org.springframework.cache.Cache.ValueWrapper;
import org.springframework.cache.support.SimpleValueWrapper;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;

/**
 * 实现cache缓存接口
 * @author Lenovo
 *
 */
public class RedisCache implements Cache{
	//缓存名称
    private String cachename;
    //redis 操作模板对象
    private RedisTemplate redisTemplate;
	public String getCachename() {
		return cachename;
	}

	public void setCachename(String cachename) {
		this.cachename = cachename;
	}

	public RedisTemplate getRedisTemplate() {
		return redisTemplate;
	}

	public void setRedisTemplate(RedisTemplate redisTemplate) {
		this.redisTemplate = redisTemplate;
	}

	@Override
	public void clear() {
		redisTemplate.execute(new RedisCallback<Integer>() {

			@Override
			public Integer doInRedis(RedisConnection connection) throws DataAccessException {
				connection.flushDb();//清除缓存数据
				return 1;
			}
		});
	}
	@Override
	public void evict(Object arg0) {
		//删除缓存
		redisTemplate.delete(arg0);
		System.out.println("删除缓存");
		
	}

	@Override
	public ValueWrapper get(Object arg0) {
		System.out.println("从存储库中的获取缓存");
		Object obj = redisTemplate.opsForValue().get(arg0);
		//如果没有得到缓存数据，返回空
		if (obj==null) {
			System.out.println("----没有缓存数据");
			return null;
		}
		ValueWrapper onjwep = new SimpleValueWrapper(obj);
		return onjwep;
	}

	@Override
	public <T> T get(Object arg0, Class<T> arg1) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String getName() {
		// TODO Auto-generated method stub
		return cachename;
	}

	@Override
	public Object getNativeCache() {
		// TODO Auto-generated method stub
		return redisTemplate;
	}

	@Override
	public void put(Object arg0, Object arg1) {
		System.out.println("讲数据放入缓存");
		//设置缓存
		redisTemplate.opsForValue().set(arg0, arg1,60,TimeUnit.SECONDS);
		
	}

	@Override
	public ValueWrapper putIfAbsent(Object arg0, Object arg1) {
		// TODO Auto-generated method stub
		return null;
	}

}